<template>
  <div class="player-list">
    <div class="list-header">
      <h2 class="list-title">{{ title }}</h2>
      <div class="list-controls">
        <div class="search-box">
          <input 
            v-model="searchQuery"
            type="text"
            placeholder="搜索玩家..."
            class="search-input"
          />
        </div>
        <div class="sort-controls">
          <select v-model="sortBy" class="sort-select">
            <option value="totalScore">按总分排序</option>
            <option value="solvedCases">按破案数排序</option>
            <option value="accuracy">按准确率排序</option>
            <option value="level">按等级排序</option>
            <option value="nickname">按昵称排序</option>
          </select>
          <button @click="toggleSortOrder" class="sort-toggle">
            {{ sortOrder === 'desc' ? '↓' : '↑' }}
          </button>
        </div>
      </div>
    </div>
    
    <div class="list-content">
      <div v-if="isLoading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="error" class="error-state">
        <p class="error-message">{{ error }}</p>
        <button @click="retry" class="retry-btn">重试</button>
      </div>
      
      <div v-else-if="filteredAndSortedPlayers.length === 0" class="empty-state">
        <p class="empty-message">{{ emptyMessage }}</p>
      </div>
      
      <div v-else class="players-grid">
        <PlayerCard
          v-for="player in filteredAndSortedPlayers"
          :key="player.id"
          :player="player"
          :current-player-id="currentPlayerId"
          :show-add-friend="showAddFriend"
          :show-view-profile="showViewProfile"
          :is-loading="isLoading"
          @add-friend="handleAddFriend"
          @remove-friend="handleRemoveFriend"
          @view-profile="handleViewProfile"
        />
      </div>
    </div>
    
    <div v-if="showPagination && totalPages > 1" class="pagination">
      <button 
        @click="goToPage(currentPage - 1)"
        :disabled="currentPage <= 1"
        class="page-btn"
      >
        上一页
      </button>
      
      <div class="page-numbers">
        <button
          v-for="page in visiblePages"
          :key="page"
          @click="goToPage(page)"
          :class="['page-btn', { active: page === currentPage }]"
        >
          {{ page }}
        </button>
      </div>
      
      <button 
        @click="goToPage(currentPage + 1)"
        :disabled="currentPage >= totalPages"
        class="page-btn"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import type { Player } from '@/entities/Player';
import PlayerCard from './PlayerCard.vue';

interface Props {
  players: Player[];
  title?: string;
  emptyMessage?: string;
  showAddFriend?: boolean;
  showViewProfile?: boolean;
  showPagination?: boolean;
  pageSize?: number;
  currentPlayerId?: string;
  isLoading?: boolean;
  error?: string | null;
}

const props = withDefaults(defineProps<Props>(), {
  title: '玩家列表',
  emptyMessage: '暂无玩家',
  showAddFriend: false,
  showViewProfile: true,
  showPagination: true,
  pageSize: 12,
  currentPlayerId: '',
  isLoading: false,
  error: null
});

const emit = defineEmits<{
  addFriend: [playerId: string];
  removeFriend: [playerId: string];
  viewProfile: [player: Player];
  retry: [];
}>();

// 状态
const searchQuery = ref('');
const sortBy = ref<keyof Player | keyof Player['stats']>('totalScore');
const sortOrder = ref<'asc' | 'desc'>('desc');
const currentPage = ref(1);

// 计算属性
const filteredAndSortedPlayers = computed(() => {
  let filtered = props.players.filter(player => {
    if (!searchQuery.value) return true;
    
    const query = searchQuery.value.toLowerCase();
    return (
      player.nickname.toLowerCase().includes(query) ||
      player.username.toLowerCase().includes(query) ||
      player.email.toLowerCase().includes(query)
    );
  });
  
  // 排序
  filtered.sort((a, b) => {
    let aValue: any, bValue: any;
    
    if (sortBy.value in a.stats) {
      aValue = a.stats[sortBy.value as keyof Player['stats']];
      bValue = b.stats[sortBy.value as keyof Player['stats']];
    } else if (sortBy.value in a) {
      aValue = a[sortBy.value as keyof Player];
      bValue = b[sortBy.value as keyof Player];
    } else {
      aValue = a.nickname;
      bValue = b.nickname;
    }
    
    if (typeof aValue === 'string') {
      aValue = aValue.toLowerCase();
      bValue = (bValue as string).toLowerCase();
    }
    
    if (sortOrder.value === 'asc') {
      return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
    } else {
      return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
    }
  });
  
  // 分页
  if (props.showPagination) {
    const start = (currentPage.value - 1) * props.pageSize;
    const end = start + props.pageSize;
    return filtered.slice(start, end);
  }
  
  return filtered;
});

const totalPages = computed(() => {
  if (!props.showPagination) return 1;
  const filtered = props.players.filter(player => {
    if (!searchQuery.value) return true;
    
    const query = searchQuery.value.toLowerCase();
    return (
      player.nickname.toLowerCase().includes(query) ||
      player.username.toLowerCase().includes(query) ||
      player.email.toLowerCase().includes(query)
    );
  });
  return Math.ceil(filtered.length / props.pageSize);
});

const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, currentPage.value - 2);
  const end = Math.min(totalPages.value, currentPage.value + 2);
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 方法
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc';
};

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
  }
};

const handleAddFriend = (playerId: string) => {
  emit('addFriend', playerId);
};

const handleRemoveFriend = (playerId: string) => {
  emit('removeFriend', playerId);
};

const handleViewProfile = (player: Player) => {
  emit('viewProfile', player);
};

const retry = () => {
  emit('retry');
};

// 监听搜索和排序变化，重置到第一页
watch([searchQuery, sortBy, sortOrder], () => {
  currentPage.value = 1;
});
</script>

<style scoped>
.player-list {
  background: var(--color-background);
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
  margin-bottom: 24px;
}

.list-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0 0 16px 0;
  color: var(--color-text);
}

.list-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  min-width: 200px;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  font-size: 14px;
  background: var(--color-background-soft);
  color: var(--color-text);
}

.search-input:focus {
  outline: none;
  border-color: var(--color-primary);
}

.sort-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.sort-select {
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  font-size: 14px;
  background: var(--color-background-soft);
  color: var(--color-text);
}

.sort-toggle {
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  color: var(--color-text);
  cursor: pointer;
  font-weight: 600;
}

.sort-toggle:hover {
  background: var(--color-background-mute);
}

.list-content {
  margin-bottom: 24px;
}

.loading-state,
.error-state,
.empty-state {
  text-align: center;
  padding: 48px 24px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--color-border);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  color: #f44336;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 8px 16px;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background: var(--color-primary-dark);
}

.empty-message {
  color: var(--color-text-secondary);
  font-style: italic;
}

.players-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-background-soft);
  color: var(--color-text);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
}

.page-btn:hover:not(:disabled) {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.active {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.page-numbers {
  display: flex;
  gap: 4px;
}

@media (max-width: 768px) {
  .list-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    min-width: auto;
  }
  
  .sort-controls {
    justify-content: space-between;
  }
  
  .players-grid {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style>